from django.contrib.auth import authenticate
from django.contrib.auth.hashers import make_password, check_password
from django.core.mail import send_mail
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpResponse
from itsdangerous import TimedJSONWebSignatureSerializer
from h2003a_mdpro import settings

import re
import redis
import uuid
import requests

from .models import *
from .sers import *
# from myutils.common import create_token, check_token, login_token
from myutils.captcha.captcha import captcha
# from myutils.authtion import Authentions
from myutils.user_util import create_token,check_token


r1 = redis.Redis(db=1)

"""
pip install celery==4.4.7
pip install redis==3.5.3
pip install eventlet==0.26.1
"""


class CheckCodeView(APIView):
    """
    验证码验证
    """
    def get(self, request):
        image_id = request.query_params.get('image_id')
        image_code = request.query_params.get('image_code')
        # 通过image_id去redis中获取验证码文本
        code_text = r1.get(image_id).decode()
        if image_code.lower() == code_text.lower():
            return Response({'msg': 'OK', 'code': 200})
        else:
            return Response({'msg': '验证码不正确', 'code': 400})


class CreateUUIDView(APIView):
    """
    uuid接口，供前端生成图片验证码使用
    """
    def get(self, request):
        image_id = str(uuid.uuid4())
        return Response({'msg': 'ok', 'image_id': image_id, 'code': 200})


class VerifyCodeView(APIView):
    """
    生成图片验证码
    """
    def get(self, request):
        # 获取图片的id
        image_id = request.query_params.get('image_id')
        # 生成图片是元组格式，需要用两个参数进行接收
        text, image = captcha.generate_captcha()
        # 把文本内容存入redis
        r1.setex(image_id, 60, text)
        # 把图片返回页面
        return HttpResponse(image, 'image/png')
        # return HttpResponse('<h1 style="color: red">Hello World</h1>')



class RegisterView(APIView):
    """
    @ author: donghaiming
    @ date: 2020-10-26
    用户注册：需要提供以下数据
        用户名、密码、确认密码、邮箱
    """
    def post(self, request):
        """
        {'username': ['zhangsan'], 'password1': ['123'], 'password2': ['123'], 'email': ['zhangsan123@qq.com']}
        """
        username = request.data.get('username')
        password1 = request.data.get('password1')
        password2 = request.data.get('password2')
        email = request.data.get('email')

        # 判断数据完整
        if not all([username, password1, password2, email]):
            return Response({'msg': '数据不完整', 'code': 400})

        # 正则验证邮箱
        ex_email = re.compile(r'^.*@[a-zA-Z0-9]{2,3}.com')
        if not re.match(ex_email, email):
            return Response({'msg': '邮箱格式不正确', 'code': 400})

        # 判断用户是否存在
        user_obj = User.objects.filter(username=username).first()
        if user_obj:
            return Response({'msg': '用户已注册', 'code': 400})

        # 两次密码验证
        if password1 == password2:
            # 构造数据
            user_data = {'username': username, 'password': make_password(password1), 'email': email}
            user_serializer = UserSer(data=user_data)
            # 校验数据
            if user_serializer.is_valid():
                user_serializer.save()
                print(user_serializer.data)
                user_id = user_serializer.data.get('id')
                # token = create_token(user_id)
                # 异步发送邮件
                subject = '美多商城会员注册'
                message = ''
                from_email = settings.EMAIL_FROM
                recipient_list = [email]
                html_message = '<h3>{},欢迎注册美多商城会员，请点击以下链接进行激活：</br><a\
href="http://127.0.0.1:8000/users/active/?user_id={}">点击激活</a></h3>'.format(username,user_serializer.data.get("id"))
                send_mail(subject=subject,
                          message=message,
                          from_email=from_email,
                          recipient_list=recipient_list,
                          html_message=html_message)
                return Response({'msg': '注册成功', 'code': 200})
            else:
                return Response({'error': user_serializer.errors, 'code': 400})
        else:
            return Response({'msg': '两次密码不一致', 'code': 400})


class ActiveView(APIView):
    def get(self,request):
        pass


class LoginView(APIView):
    # 后台登录接口

    def post(self,request):
        # 接收前台发送的数据
        username = request.data.get("username")
        password = request.data.get("password")
        # 使用authenticate进行登录验证
        user = authenticate(username=username,password=password) #登录不成功的话返回None
        if user:
            print(user)
            user_id = user.pk
            token = create_token(user_id)
            return Response({"msg":"ok","code":200,"user_id":user_id,"token":token})
        # 未通过验证，返回登录失败
        else:
            return Response({"msg":"登录失败"})